"use strict";

// const Controller = require("egg").Controller;
const jwt = require("jsonwebtoken");
const shortid = require("shortid");
const md5Hex = require("md5-hex");
const BaseController = require("../core/base_controller");

// const  key = require('../utils/index');
class UserController extends BaseController {
  async index() {
    const _ctx = this.ctx;
    const user = await _ctx.model.User.findById(3);
    _ctx.body = user;
  }
  //注册
  async creat() {
    const _ctx = this.ctx;
    const validator = this.app.validator;
    try {
      const status = _ctx.validate(validator.userV.registeUser);
      if (status.error) {
        this.validateFail(status.error.details[0].message); // "参数格式错误"
      } else {
        const params = _ctx.request.body;
        const haveReferral = await isHaveReferalCode(params.referralCode);
        console.log("推荐码是否正确=", haveReferral)
        if (!haveReferral) {
          // && params.referralCode != '08080808' 必须有推荐码才能注册
          this.validateFail("错误的推荐码" + params.referralCode);
          return;
        }
        //先核对验证码,可一定程度造成非法注册的难度
        let UUID = _ctx.header.token; //假的token名,实际是设备的UUID
        const isCapctcha = await _ctx.model.Captcha.findAll({
          where: {
            $and: [{
                capctcha: params.smsCode
              },
              {
                deviceUUID: UUID
              }
            ]
          }
        });
        if (isCapctcha.length > 0) {
          const time = _ctx.helper.timeDiff(
            _ctx.helper.moment(),
            isCapctcha[0].dataValues.updated_at
          );
          // console.log("moment>>>>>>>>>>>>>", time / 60000)
          if (time / 60000 > 5) {
            //如果大于5分钟
            this.validateFail("验证码时效已过,请刷新验证码");
            return;
          }
        }
        if (isCapctcha.length == 0) {
          this.validateFail("验证码错误");
          return;
        }

        if (!Number(params.userPhone)) {
          //必须数字字符的手机号码才行
          this.validateFail("错误的数据格式");
          return;
        }
        const isHave = await _ctx.model.User.findAll({
          where: {
            userPhone: params.userPhone
          }
        });
        // console.log("接收到的传参0", params);
        // console.log("查询到的数据多少", isHave.length);
        if (isHave.length != 0) {
          this.fail("已注册过,请勿重复注册");
        } else {
          let userCode = shortid.generate(); //生成推荐码
          const isUserCode = await _ctx.model.User.findAll({
            //先查一次,防止重复,不能放在create后
            where: {
              userCode: userCode
            }
          });
          // const machineList = makeMachineList(userCode);
          let md5Pasword = params.userPwd; // 前端已加密 md5Hex(params.userPwd); //md5加密密码再保存
          md5Pasword =
            md5Pasword.substring(0, 2) +
            md5Pasword.substring(3, md5Pasword.length);
          const user = await _ctx.model.User.create({
            userPwd: md5Pasword,
            userPhone: params.userPhone,
            referralCode: params.referralCode,
            userCode: userCode, //自己的推荐码
            whoseProxy: haveReferral.whoseProxy, //代理伞下标志  
            UUID:UUID,//注册时的设备id
            // machineList: machineList
          });
          this.success({}, "恭喜您注册成功!成功的大门已经为你打开");
          //haveReferral[0].id
          await _ctx.model.User.update({
            //要更新推荐人的人数
            recommendedAmount: haveReferral.recommendedAmount + 1
          }, {
            where: {
              id: haveReferral.id
            }
          });
          await _ctx.model.Captcha.destroy({
            ////删除验证码
            where: {
              id: isCapctcha[0].dataValues.id
            }
          });
          //以下防止推荐码重复,再判断一次,有则在已创建基础上把id也加入.确保唯一性
          if (isUserCode.length > 0) {
            const id = user.dataValues.id;
            userCode = id + "-" + userCode;
            await _ctx.model.User.update({
              userCode: userCode
            }, {
              where: {
                id: id
              }
            });
          }
        }
      }
    } catch (e) {
      console.log("错误了", e);
      _ctx.body = String(e);
    }

    //查推荐码
    async function isHaveReferalCode(referralCode) {
      //
      const code = await _ctx.model.User.findOne({
        where: {
          userCode: referralCode //查所有用户的推荐码
        }
      });
      return code;
    }

    // function makeMachineList(id) {
    //   // let arr = [];
    //   // for (let i = 0; i < 20; i++) {
    //   //   arr.push({
    //   //     name: "广告浏览机器人",
    //   //     text: "v8新一代广告机器人",
    //   //     price: 299,
    //   //     id: id + "-" + i,
    //   //     isBuy: 0, //0 未订的
    //   //     isOrder: 0 //未下单的
    //   //   });
    //   // }
    //   return '' // JSON.stringify(arr);
    // }
  }

  //查看个人信息时二次确认密码
  async verifyPsw() {
    const {
      ctx
    } = this;
    const param = ctx.request.body;
    const user = await ctx.model.User.findById(param.id, {
      attributes: ["userPwd"]
    });
    const psw = ctx.helper.restore(param.psw);
    if (user && psw == user.userPwd) {
      this.success({}, "ok");
    } else {
      this.validateFail("密码错误"); // "参数格式错误"
    }
  }
  //用户查个人收益
  async userProfit() {
    const {
      ctx
    } = this;
    const p = ctx.request.body;
    const list = await ctx.model.WithdrawHistory.findAll({
      where: {
        userId: p.id
      },
      order: [
        ['createdAt', 'DESC'],
      ],
    });
    this.success({
        list: list
      },
      "ok"
    );
  }

  //签到
  // 
  async signIn() {
    let that = this;
    const {
      ctx,
      service
    } = this;
    const {
      col
    } = this.app.Sequelize; //col 是配合  raw:true
    const p = ctx.request.body;

    if (!p.id) {
      this.validateFail("参数错误");
      return;
    }
    const isUser = await ctx.model.Token.findOne({
      attributes: [
        col("user.id"),
        col("user.deposit"),
        col("user.signIn"),
        col("user.orderPay"),
        col("user.isVip"),
        col("user.buyCount")
      ], //
      where: {
        token: ctx.header.token
        // id: p.id,
      },
      include: [{
        model: ctx.model.User,
        as: "user", //联合一定要加别名
        attributes: [] //加此空的比较好
      }],
      raw: true //为 true时  上面的col才能正常使用
    });

    if (!isUser) {
      ctx.throw(401, "invalid token");
      this.fail("您无权限");
    } else if (isUser.id != p.id) {
      this.fail("参数错误!");
    } else if (isUser.isVip == 1) {
      await service.isService.isCanSign(p.id)
      if (isUser.signIn) {
        let flag = isSiginFun(isUser.signIn, this)
        // console.log("=====",flag);
        if (flag > 0) {
          await updateSignIn(ctx, isUser);
        }
      } else {
        // console.log("未的", isUser.signIn);
        await updateSignIn(ctx, isUser);
      }
    } else {
      this.fail("开通会员后才能获得分润哦!");
    }
    //检测时间
    function isSiginFun(date, that) {
      // let that  =this;
      let now = ctx.helper.moment(new Date());
      let b = ctx.helper.moment(date);
      //  console.log("时间差",now.diff(b));//负的则是后面的日期 
      if (now.diff(b) < 0) {
        that.fail("请于 " + ctx.helper.moment(date).format('YYYY年MM月DD日 HH:mm:ss') + "后再启动AI")
        return -1
      }
      if (ctx.helper.moment().format("YYYY-MM-DD") == ctx.helper.moment(date).format("YYYY-MM-DD")) {
        ctx.throw("isSigined");
        return 0
      }
      return 1
    }
    async function updateSignIn(ctx, user) {
      const rate = ctx.helper.cache.get(ctx.YIELD_RATE);
      let yieldRate = 0;
      if (rate) {
        yieldRate = rate;
        //  console.log("=收益率==", yieldRate);
      } else {
        let sys = await ctx.model.System.findById(1);
        // console.log("===收益率-", sys.yieldRate);
        yieldRate = sys.yieldRate;
        ctx.helper.cache.put(ctx.YIELD_RATE, sys.yieldRate);
      }

      let m = user.orderPay * yieldRate;
      // console.log(user.orderPay, yieldRate, "此次得到", Number(m.toFixed(2)));
      m = Number(m.toFixed(2));
      const now = ctx.helper.moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
      const isOK = await ctx.model.User.update({
        signIn: now
      }, {
        where: {
          id: user.id
        }
      });

      const kk = await ctx.model.User.increment({
        deposit: m
      }, { //打卡收益更新
        where: {
          id: user.id
        }
      })

      const isOK2 = await ctx.model.WithdrawHistory.create({
        money: m,
        userId: user.id,
        historyType: 2
      });
      if (isOK && isOK2 && kk) {
        // console.log(isOK, now);
        that.success({}, "AI成功开启");
      } else {
        that.fail("AI开启失败,请稍后再试或咨询客服");
      }
      return "";
    }
  }
  //提现余额查询
  async getMyBalance() {
    const {
      ctx
    } = this;
    const param = ctx.request.body;
    // console.log(ctx.body, "=====", param);
    const user = await ctx.model.User.findById(param.id, {
      attributes: ["id", "deposit"]
    });
    // console.log(user);
    if (!user) {
      this.fail("没有此用户");
      return;
    }

    this.success({
        data: user
      },
      "ok"
    );
  }
  //保存个人信息
  async saveInfo() {
    const {
      ctx
    } = this;
    const param = ctx.request.body;
    const token = ctx.header.token;
    const isToken = await ctx.model.Token.find({
      where: {
        token: token
      }
    });
    // console.log(param, "=====角密前=======");
    console.log(isToken)

    let obj = ctx.helper.decode(param.head);
    obj = JSON.parse(obj);
    // console.log(isToken.userId, "--解密--", obj.id);
    if (!isToken || isToken.userId != obj.id) {
      this.validateFail("信息错误");
      return;
    }
    let data = {
      firstPay: obj.firstPay,
      age: obj.age,
      sex: obj.sex,
      email: obj.email
    };

    if (obj.alipay || obj.aliPayee) {
      data.alipay = obj.alipay;
      data.aliPayee = obj.aliPayee;
    } else if (obj.wxPayee || obj.wechart) {
      data.wxPayee = obj.wxPayee;
      data.wechart = obj.wechart;
    } else if (obj.bankPayee) {
      data.bankPayee = obj.bankPayee;
      data.bankCard = obj.bankCard;
      data.bankName = obj.bankName;
    }
    // console.log(data, "----------");
    await ctx.model.User.update(data, {
      where: {
        id: obj.id
      }
    });
    // if(user){
    // this.fail("error");
    // }
    this.success({}, "ok");
  }
  //注册用  验证码
  async getVerify() {
    const _ctx = this.ctx;
    console.log("UUID=", _ctx.header.token);
    // console.log(shortid.generate( ));
    let UUID = _ctx.header.token; //假的token名
    if (UUID) {
      const captcha = await this.service.tools.captcha();
      this.ctx.response.type = "image/svg+xml";
      console.log("验证码", captcha.text);
      this.ctx.body = captcha.data;
      //  {
      //   success:true,
      //   status:0,
      //   data:captcha.data
      // }

      const isHave = await _ctx.model.Captcha.findAll({
        where: {
          deviceUUID: UUID
        }
      });
      if (isHave.length) {
        //有则更新
        // console.log("有", isHave[0].dataValues.created_at)
        // console.log(Date.parse(isHave[0].dataValues.created_at))
        await _ctx.model.Captcha.update({
          capctcha: captcha.text
        }, {
          where: {
            deviceUUID: UUID
          }
        });
      } else {
        await _ctx.model.Captcha.create({
          deviceUUID: UUID,
          capctcha: captcha.text
        });
      }
    } else {
      this.ctx.body = {
        success: false,
        status: 1,
        msg: "url参数名:userName,是必须的" //加入混淆
      };
    }
  }

  //获取个人信息 信息要脱免
  async getUserInfo() {
    const {
      ctx
    } = this;
    const params = ctx.query;
    const token = ctx.header.token;
    const isToken = await ctx.model.Token.find({
      //二次
      where: {
        token: token
      }
    });
    if (!isToken || isToken.userId != params.id) {
      this.validateFail("信息错误");
      return;
    }
    console.log("ok---------------", isToken);
    const user = await ctx.model.User.findById(params.id, {
      // attributes: ['id',  ],
      attributes: {
        exclude: [
          "id",
          "userPwd",
          "wechart",
          "isVip",
          "buyCount",
          "alipay",
          "userCode",
          "isAdmin",
          "deposit",
          "machineList",
          "recommendedAmount",
          "createdAt",
          "updatedAt",
          "deletedAt",
          "whoseProxy",
        ]
      } //排除 密码
    });
    let usr = user.dataValues;
    usr.userPhone =
      usr.userPhone.substring(0, 2) +
      "****" +
      usr.userPhone.substring(6, usr.userPhone.length);

    let str = JSON.stringify(user.dataValues);
    let base = ctx.helper.base64url(str);
    // console.log("个人信息", params, user.dataValues, ); //
    base =
      "image/png;base64," +
      base.substring(0, 2) +
      "1" +
      base.substring(2, base.length);
    this.success({
        data: base
      },
      "ok"
    );
  }
  //app用户tx申请
  async applicatioWithdrawal() {
    const {
      ctx
    } = this;
    const params = ctx.request.body;
    const token = ctx.header.token;
    try {
      const isToken = await ctx.model.Token.findOne({
        where: {
          token: token
        }
      });

      if (isToken.userId === ctx.helper.parseInt(params.id)) {
        //id也要相等
        // console.log("--", typeof isToken.userId)
        //查用户余额够不够限额
        const isEnough = await ctx.model.User.findById(params.id, {
          attributes: ["id", "isVip", "deposit"]
        });
        const data = isEnough.dataValues;
        if (data.isVip === 1 && data.deposit > ctx.MAXI_MUM_WITHDRAWAL) {
          // isVip: 1, deposit
          const isHave = await ctx.model.ApplicationWithdrawal.findAll({
            //查有没有已经申请过了的
            where: {
              $and: [{
                  userId: params.id
                },
                {
                  status: 0 //0 为正在申请的
                }
              ]
            }
          });
          if (isHave.length > 0) {
            this.fail("您已经有一笔在申请,请在通过后再申请");
          } else {
            // console.log(ctx.MAXI_MUM_WITHDRAWAL)
            await ctx.model.ApplicationWithdrawal.create({
              userId: params.id,
              applicationMoney: params.num, //申请额只能是ctx.MAXI_MUM_WITHDRAWAL的倍数 applicationMoney
              status: 0, //0 是申请的  ,
              userRemarks: params.remarks
            });
            this.success({}, "申请提现成功");
          }
        } else {
          this.fail("您还未达到可提额");
        }
      } else {
        this.fail("请联系客服");
      }
    } catch (e) {
      this.fail("请联系客服!");
    }
  }
  async isOrderBuy() {
    const {
      ctx
    } = this;
    const p = ctx.request.body;
    const isHave = await ctx.model.OrderBuy.find({
      where: {
        userId: p.id
      }
    });
    console.log("--", isHave);
    if (isHave) {
      this.fail("已经下过单,请审核成功过后再下单");
    } else {
      this.success({}, "可以");
    }
  }
  //app用户下单
  async orderBuy() {
    const {
      ctx
    } = this;
    const validator = this.app.validator;
    //orderBuy
    const statusV = ctx.validate(validator.orderBuyV.orderBuy);
    console.log("验证", statusV);
    if (statusV.error) {
      this.validateFail(statusV.error.details[0].message); // "参数格式错误"
    } else {
      const p = ctx.request.body;
      console.log("参数", p);
      const param = {
        status: 1,
        userPayName: p.userPayName,
        payType: p.payType,
        orderCount: p.orderCount,
        orderMoney: p.orderMoney,
        userId: p.id
      };
      const isHave = await ctx.model.OrderBuy.create(param
        // {
        // defaults: {
        //   ...param
        // },
        // where: {
        //   userId: p.id
        // }
        // }
      );
      console.log(isHave, "ppp")
      if (isHave) {
        this.success({}, "下单成功,请等待通知!");
      } //else {
      //   // await ctx.model.OrderBuy.create(param)
      //   this.success(
      //     {
      //       data: p
      //     },
      //     "ok"
      //   );
      // }
    }
  }
   
  async getUserOrderBuy(){
    const {
      ctx
    } = this;
    const p = ctx.request.body;
    const tokenId = ctx.header.tokenid;
    if(p.id!=tokenId){//假别人的用户
      ctx.throw(401, "invalid token");
       console.log("应该不会执行");
    }
    const isHave = await ctx.model.OrderBuy.findAll({
      where: {    
        userId: p.id, 
      },
      paranoid: false,//可查假删除的数据
    });

    this.success({list:isHave},"查询成功0")
  }

  //测试表关联查询
  async find(id) {
    const {
      col
    } = this.app.Sequelize; //col 是配合  raw:true
    const UserInfo = await this.ctx.model.UserInfo.findAll({
      //要确保userInfo 的主键id =1
      attributes: [col("user.userPhone"), col("user.userName"), "id"],
      include: [{
        model: this.ctx.model.User,
        as: "user", //联合一定要加别名'user'
        attributes: []
      }],
      where: {
        // id:1 ,
        userId: 2 //可再加入条件
      },
      raw: true //为 true时  上面的col才能正常使用
    });

    // console.log("================",JSON.stringify(UserInfo.dataValues)) //UserInfo
    // console.log("================" ,)

    this.ctx.body = UserInfo;

    // this.ctx.body= {...UserInfo};
  }
}

module.exports = UserController;
//function getNow() {
//   let date = new Date();
//   date =
//     date.getFullYear() +
//     "-" +
//     (Number(date.getMonth()) + 1) +
//     "-" +
//     date.getDate() +
//     " " +
//     date.getHours() +
//     ":" +
//     date.getMinutes() +
//     ":" +
//     date.getSeconds();
//   // console.log("现在时间为:", date)
//   return date;
// }
//登录 userLoginV

//  async login() {
//   // this.ctx.coreLogger.info(`APP登录 测试生产能还否打印 `); //会打印到egg.web.log文件中
//   const _ctx = this.ctx;
//   const {
//     service
//   } = this.ctx;
//   const validator = this.app.validator;
//   try {
//     const status = _ctx.validate(validator.userLoginV.userLogin);
//     if (status.error) {
//       this.validateFail("帐号或密码错误"); // "参数格式错误"
//     } else {
//       const params = _ctx.request.body;
//       // console.log("参数", params);
//       const isUser = await _ctx.model.User.findAll({ //先查一次,防止重复,不能放在create后
//         where: {
//           userPhone: params.userPhone,
//         },
//         attributes: ['id', 'userPwd', "userCode"]
//       });
//       let md5Pasword = params.userPwd; //前端已经加密 md5Hex(params.userPwd);
//       md5Pasword = _ctx.helper.restore(md5Pasword);
//       // md5Pasword = md5Pasword.substring(0, 2) + md5Pasword.substring(3, md5Pasword.length)
//       // console.log(md5Pasword, isUser[0].userPwd)
//       if (isUser.length > 0 && md5Pasword == isUser[0].userPwd) {
//         const id = isUser[0].id
//         const token = await service.tools.token Sign(id, params.userPhone); //生成token
//         // console.log(id, "登录token", isUser)
//         await _ctx.model.Token.upsert({ //或用别名:insertOrUpdate
//           id: id,
//           token: token,
//           userId: _ctx.helper.parseInt(id) //id,
//         })
//         //后期可增加登录后把设备信息存储起来
//         this.success({
//           userCode: isUser[0].userCode,
//           id: id,
//           token: token,
//         }, "登录成功!你已经进入了成功的大门!");
//       } else {
//         this.validateFail("帐号或密码错误2"); // "参数格式错误"
//       }
//     }
//   } catch (e) {}
// }